package com.ck.util;

import com.ck.constant.ClientConstant;
import com.ck.constant.NormalStrConstant;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ajax请求相关常量
 *
 * @author linqiang
 * @version v1.0
 * @date 2018-10-24 15:30
 */
public class AjaxUtils {

    /**
     * 判断是否是ajax请求
     *
     * @param request 请求
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        boolean isAjax = false;
        if (request.getHeader(NormalStrConstant.X_REQUESTED_WITH) != null
                && NormalStrConstant.XML_HTTP_REQUEST.equals(request.getHeader(NormalStrConstant.X_REQUESTED_WITH))) {
            isAjax = true;
        }
        return isAjax;
    }

    /**
     * 未登录时对ajax请求的处理
     *
     * @param response 响应
     */
    public static void writeNeedLoginResultForAjax(HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        ObjectMapper json = new ObjectMapper();
        map.put("code", ClientConstant.CODE_NOT_LOGIN);
        map.put("msg", ClientConstant.MSG_NOT_LOGIN);
        response.setContentType("text/javascript;charset=utf-8");
        response.getWriter().write(json.writeValueAsString(map));
        response.sendError(ClientConstant.CODE_NOT_LOGIN, "访问被限制，请先登录");
    }
}
